<template>
	<el-card shadow="hover">
		<el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
			<el-form-item label="用户ID" prop="user_id">
				<el-input v-model="queryParams.user_id" placeholder="请输入昵称" clearable />
			</el-form-item>
			<el-form-item label="申请时间段" prop="time">
				<el-date-picker
					v-model="queryParams.time"
					type="daterange"
					range-separator="~"
					start-placeholder="开始时间"
					end-placeholder="结束时间"
					value-format="X"
					:default-time="defaultTime"
				/>
			</el-form-item>
			<el-form-item v-if="queryParams.status === '2'" label="状态/打款状态" prop="type">
				<el-select v-model="queryParams.type">
					<el-option label="转账成功" value="1" />
					<el-option label="转账中" value="0" />
					<el-option label="转账失败" value="2" />
					<el-option label="打款中" value="3" />
					<el-option label="打款失败" value="4" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="onQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="onResetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="top-block mb8">
			<el-col :span="1.5">
				<el-button v-if="queryParams.status === '1'" @click="onAudit" type="primary" plain :disabled="multiple">审核</el-button>
				<el-button v-if="queryParams.type === '1'" @click="onRemit" type="primary" plain :disabled="multiple">打款</el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
		</el-row>
		<el-tabs type="border-card" v-model="queryParams.status">
			<el-tab-pane label="待审核" name="1" />
			<el-tab-pane label="转账/打款" name="2" />
			<el-tab-pane label="审核拒绝" name="3" />
			<el-tab-pane label="打款完成" name="4" />
		</el-tabs>
		<el-table :data="tableList" v-loading="loading" @selection-change="onSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="编号" align="center" prop="id" />
			<el-table-column label="申请用户信息" align="center" prop="users">
				<template #default="{ row }">
					<div style="text-align: left">ID：{{ row.user_id }}<br />姓名：{{ row.users.nickname }}<br />身份：{{ formatterIdentity(row) }}</div>
				</template>
			</el-table-column>
			<el-table-column label="商户号" align="center" prop="mchid" />
			<el-table-column label="提现金额" align="center" prop="apply_money" />
			<el-table-column label="税费" align="center" prop="tax_money" />
			<el-table-column label="到账金额" align="center" prop="need_remit_money" />
			<el-table-column label="预计到账卡号" align="center" prop="bank_number" />
			<template v-if="queryParams.status === '2'">
				<el-table-column label="转账单号" align="center" prop="third_trx_no" :formatter="formatterThirdTrxOn" />
				<el-table-column label="转账状态" align="center" prop="zhuanzhang_status" :formatter="formatterZhuanZhangStatus" />
				<el-table-column label="转账失败原因" align="center" prop="fail_reason">
					<template #default="{ row }">
						<el-tooltip v-if="row.zhuanzhang && row.zhuanzhang.fail_reason" effect="light" :content="row.zhuanzhang.fail_reason" placement="top">
							<el-button>查看</el-button>
						</el-tooltip>
						<span v-else>----</span>
					</template>
				</el-table-column>
			</template>
			<template v-if="Number(queryParams.type) > 2">
				<el-table-column label="打款单号" align="center" prop="mch_settle_no" :formatter="formatterMchSettleOn" />
				<el-table-column label="打款状态" align="center" prop="payment_status" :formatter="formatterPaymentStatus" />
				<el-table-column label="打款失败原因" align="center" prop="payment_fail_reason">
					<template #default="{ row }">
						<el-tooltip v-if="row.dakuan.payment_fail_reason" effect="light" :content="row.dakuan.payment_fail_reason" placement="top">
							<el-button>查看</el-button>
						</el-tooltip>
						<span v-else>----</span>
					</template>
				</el-table-column>
			</template>
			<template v-if="queryParams.status === '4'">
				<el-table-column label="到账卡号" align="center" prop="account_number" :formatter="formatterAccountNumber" />
				<el-table-column label="打款单号" align="center" prop="mch_settle_no" :formatter="formatterMchSettleOn" />
			</template>
			<el-table-column label="状态" align="center" prop="status" :formatter="formatterStatus" />
			<el-table-column v-if="queryParams.status === '3'" label="拒绝原因" align="center" prop="cancel_reason">
				<template #default="{ row }">
					<el-tooltip v-if="row.cancel_reason" effect="light" :content="row.cancel_reason" placement="top">
						<el-button>查看</el-button>
					</el-tooltip>
					<span v-else>----</span>
				</template>
			</el-table-column>
			<el-table-column label="时间轴" align="center">
				<template #default="{ row }">
					<el-popover placement="top" title="时间轴" :width="260" trigger="hover">
						<template #reference>
							<el-button>查看</el-button>
						</template>
						<div>
							申请时间：{{ formatterTime(row.apply_time) }}<br />
							审核时间：{{ row.check_time1 ? formatterTime(row.check_time1) : '----' }}<br />
							转账开始时间：{{ row.zhuanzhang ? formatterTime(row.zhuanzhang.start_time) : '----' }}<br />
							转账结束时间：{{ row.zhuanzhang ? formatterTime(row.zhuanzhang.notify_time) : '----' }}<br />
							打款开始时间：{{ row.dakuan ? formatterTime(row.dakuan.payment_start_time) : '----' }}<br />
							打款结束时间：{{ row.dakuan ? formatterTime(row.dakuan.payment_notify_time) : '----' }}<br />
						</div>
					</el-popover>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" fixed="right">
				<template #default="{ row }">
					<el-tooltip v-if="queryParams.type === '1'" effect="light" :content="meerchantBalance" placement="top" trigger="click">
						<el-button type="text" @click="onViewMerchantBalance(row)">查看商户余额</el-button>
					</el-tooltip>
				</template>
			</el-table-column>
		</el-table>
		<pagination-component
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>
		<auditDialog ref="auditDialogRef" />
	</el-card>
</template>

<script>
import { getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { withdrawalApi } from '/@/api/admin';
import { timeDictionary } from '/@/utils/dictionaryTranslation';

import auditDialog from './dailog/auditDialog.vue';

const WithdrawalApi = withdrawalApi();
export default {
	name: 'commissionAudit',
	components: { auditDialog },
	data() {
		const { proxy } = getCurrentInstance();
		return {
			showSearch: true,
			queryParams: {
				user_id: '',
				status: '1',
				type: '0',
				time: [],
				pageNum: 1,
				pageSize: 10,
			},
			tableList: [],
			loading: false,
			total: 0,
			multiple: true,
			meerchantBalance: '',
			defaultTime: [
				new Date(proxy.dayjs().year(), proxy.dayjs().month(), proxy.dayjs().date(), 0, 0, 0),
				new Date(proxy.dayjs().year(), proxy.dayjs().month(), proxy.dayjs().date(), 23, 59, 59),
			],
		};
	},
	created() {
		this.getList();
	},
	methods: {
		/********** 触发事件 **********/
		// 搜索
		onQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		// 重置
		onResetQuery() {
			this.$refs.queryFormRef.resetFields();
			this.onQuery();
		},
		// 审核 - 转账
		onAudit() {
			const ids = this.selectionInfo.map((item) => item.id).join(',');
			this.$refs.auditDialogRef.openDialog({ ids }, () => this.getList());
		},
		// 审核 - 打款
		onRemit() {
			const ids = this.selectionInfo.map((item) => item.id).join(',');
			ElMessageBox.prompt('操作密码', '打款', {
				confirmButtonText: '提交',
				cancelButtonText: '取消',
				inputPlaceholder: '请输入操作密码',
				beforeClose: (action, instance, done) => {
					console.log('action, instance', action, instance);
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						this._withdrawalPaymentBatch({ withdraw_ids: ids, password: instance.inputValue }, done, instance);
					} else {
						done();
					}
				},
			})
				.then(() => {})
				.catch(() => {});
		},
		// 查看商户余额
		onViewMerchantBalance(row) {
			this.meerchantBalance = '';
			this._withdrawalBalance({ user_id: row.user_id });
		},
		// 选择数据
		onSelectionChange(selection) {
			this.multiple = !selection.length;
			this.selectionInfo = selection;
		},

		/********** 方法事件 **********/
		// 刷新列表
		getList() {
			this.loading = true;
			switch (Number(this.queryParams.status)) {
				case 1:
					this._withdrawalToBeReviewed({
						...this.queryParams,
						start_time: this.queryParams.time ? this.queryParams.time[0] : '',
						end_time: this.queryParams.time ? this.queryParams.time[1] : '',
					});
					break;
				case 2:
					this._withdrawalPaymentApproved({
						...this.queryParams,
						start_time: this.queryParams.time ? this.queryParams.time[0] : '',
						end_time: this.queryParams.time ? this.queryParams.time[1] : '',
					});
					break;
				case 3:
					this._withdrawalAuditRejection({
						...this.queryParams,
						start_time: this.queryParams.time ? this.queryParams.time[0] : '',
						end_time: this.queryParams.time ? this.queryParams.time[1] : '',
					});
					break;
				case 4:
					this._withdrawalApproved({
						...this.queryParams,
						start_time: this.queryParams.time ? this.queryParams.time[0] : '',
						end_time: this.queryParams.time ? this.queryParams.time[1] : '',
					});
					break;
			}
		},
		// 身份字典
		formatterIdentity(row) {
			switch (row.identity) {
				case 1:
					return '普通用户';
				case 2:
					return '代理';
				case 3:
					return '经理';
				default:
					return '未知错误';
			}
		},
		// 时间字典
		formatterTime(time) {
			return timeDictionary(time);
		},
		// 状态字典
		formatterStatus(row) {
			switch (row.status) {
				case 1:
					return '待审核';
				case 2:
					return '审核通过待打款';
				case 3:
					return '审核拒绝';
				case 4:
					return '打款成功';
				case 5:
					return '打款失败';
				default:
					return '未知错误';
			}
		},
		// 转账单号字典
		formatterThirdTrxOn(row) {
			return row.zhuanzhang && (row.zhuanzhang.third_trx_no || '----');
		},
		// 转账状态字典
		formatterZhuanZhangStatus(row) {
			if (!row.zhuanzhang) {
				return '';
			}
			if (!Object.keys(row.zhuanzhang).length) {
				return '转账中';
			}
			switch (row.zhuanzhang.status) {
				case 'P1000':
					return '交易成功';
				case 'P2000':
					return '交易失败';
				case 'P3001':
					return '处理中';
				default:
					return '未知错误';
			}
		},
		// 打款单号字典
		formatterMchSettleOn(row) {
			return row.dakuan && (row.dakuan.mch_settle_no || '----');
		},
		// 到账卡号字典
		formatterAccountNumber(row) {
			return row.dakuan && (row.dakuan.account_number || '----');
		},
		// 打款状态字典
		formatterPaymentStatus(row) {
			if (!row.dakuan) {
				return '';
			}
			if (!Object.keys(row.dakuan).length) {
				return '打款中';
			}
			if (row.dakuan) {
				switch (row.dakuan.payment_status) {
					case '0':
						return '未打款';
					case 'P1000':
						return '交易成功';
					case 'P2000':
						return '交易失败';
					case 'P3000':
						return '结果未知';
					case 'P3001':
						return '处理中';
					default:
						return '未知错误';
				}
			}
		},

		/********** 网络请求 **********/
		// 待审核
		_withdrawalToBeReviewed(params) {
			WithdrawalApi.withdrawalToBeReviewed(params)
				.then((res) => {
					this.tableList = res.data.list;
					this.total = res.data.total;
					this.loading = false;
				})
				.catch(() => (this.loading = false));
		},
		// 打款中
		_withdrawalPaymentApproved(params) {
			WithdrawalApi.withdrawalPaymentApproved(params)
				.then((res) => {
					this.tableList = res.data.list;
					this.total = res.data.total;
					this.loading = false;
				})
				.catch(() => (this.loading = false));
		},
		// 审核拒绝
		_withdrawalAuditRejection(params) {
			WithdrawalApi.withdrawalAuditRejection(params)
				.then((res) => {
					this.tableList = res.data.list;
					this.total = res.data.total;
					this.loading = false;
				})
				.catch(() => (this.loading = false));
		},
		// 完成
		_withdrawalApproved(params) {
			WithdrawalApi.withdrawalApproved(params)
				.then((res) => {
					this.tableList = res.data.list;
					this.total = res.data.total;
					this.loading = false;
				})
				.catch(() => (this.loading = false));
		},
		// 审核 - 打款
		_withdrawalPaymentBatch(params, done, instance) {
			WithdrawalApi.withdrawalPaymentBatch(params)
				.then(() => {
					ElMessage.success('操作成功');
					instance.confirmButtonLoading = false;
					done();
					this.getList();
				})
				.catch(() => (instance.confirmButtonLoading = false));
		},
		// 查看商户余额
		_withdrawalBalance(params) {
			WithdrawalApi.withdrawalBalance(params).then((res) => {
				this.meerchantBalance = res.data.info.money;
			});
		},
	},
	watch: {
		'queryParams.status': {
			handler: function (val) {
				if (val === '2') {
					this.queryParams.type = '1';
				} else {
					this.queryParams.type = '0';
				}
				this.getList();
			},
		},
		'queryParams.type': {
			handler: function () {
				this.getList();
			},
		},
	},
};
</script>
